using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Security;
using System.Threading;

namespace RStein.Posterous.API
{
    internal class PosterousAccount : IPosterousAccount, IEquatable<PosterousAccount>
    {
        
        #region private fields
        private List<IPosterousSite> m_sites;
        private readonly string m_userName;
        private readonly string m_password;
        private bool m_sitesLoaded;
        #endregion private fields

        #region Constructors

        
        public PosterousAccount(IPosterousApplication application, string userName, string password)
        {

            if (application == null)
            {
                throw new ArgumentNullException("application");
            }
         
            if (userName == null)
            {
                throw new ArgumentNullException("userName");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            
            
            Application = application;
            m_userName = userName;
            m_password = password;
            m_sitesLoaded = false;
        }

        #endregion Constructors
        #region Properties
        internal string Password
        {
            get
            {
                return m_password;
            }
        }
        

        #endregion Properties
        #region methods
        private void ensureSitesLoaded()
        {
            if (!m_sitesLoaded)
            {
                LoadSites();
            }
        }
        public bool Equals(PosterousAccount other)
        {
            if (ReferenceEquals(null, other))
            {
                return false;
            }
            if (ReferenceEquals(this, other))
            {
                return true;
            }
            return Equals(other.m_userName, m_userName);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }
            if (ReferenceEquals(this, obj))
            {
                return true;
            }
            if (obj.GetType() != typeof (PosterousAccount))
            {
                return false;
            }
            return Equals((PosterousAccount) obj);
        }

        public override int GetHashCode()
        {
            return m_userName.GetHashCode();
        }

        

        public static bool operator ==(PosterousAccount left, PosterousAccount right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(PosterousAccount left, PosterousAccount right)
        {
            return !Equals(left, right);
        }

        protected virtual void OnSitesLoaded(EventArgsValue<IEnumerable<IPosterousSite>> e)
        {
            EventHandler<EventArgsValue<IEnumerable<IPosterousSite>>> handler = SitesLoaded;
            if (handler != null)
            {
                Thread.CurrentThread.GetCurrentSynchronizationContext().Post(o => handler(this, e), null);
            }
        }
        #endregion methods

        #region Implementation of IExtensionInterface

        public T GetInterface<T>() where T : class
        {


            return this as T;
            
        }

        #endregion

        #region Implementation of IPosterousAccount

        public string Name
        {
            get
            {
                return m_userName;
            }
        }

        public IEnumerable<IPosterousSite> Sites
        {
            get
            {  
                ensureSitesLoaded();
                return m_sites;
            }
        }

        public IPosterousSite PrimarySite
        {
            get
            {
                ensureSitesLoaded();
                return m_sites.Where(site => site.IsPrimary).SingleOrDefault();
            }
        }

        
        public IPosterousApplication Application
        {
            get; 
            set;
        }

        public virtual void LoadSites()
        {
                var builder = SimpleWebFactory.Instance.Create<IPosterousRequestBuilder>();

                builder.StartBuildWebRequest(GlobalConstants.URL_GET_SITES);
                builder.BuildHttpAuthentication(m_userName, m_password);

                WebResponse response = builder.GetResponse();
                var responseBuilder = new PosterousResponseBuilder();
                var parserInstance = new SitesResponseParser();
                Func<Stream, IEnumerable<IPosterousSite>> parser = parserInstance.GetResults;
                m_sites = responseBuilder.ParseResponse(response, parser).ToList();
                m_sites.ForEach(site => site.PosterousAccount = this);

                Debug.Assert(m_sites != null);

                m_sitesLoaded = true;
                OnSitesLoaded(new EventArgsValue<IEnumerable<IPosterousSite>>(m_sites, null));
            
        }

        public virtual void LoadSitesAsync()
        {

            Action<Exception> exchandler = e =>
            {
                new PosterousException(GlobalConstants.ASYNC_EXCEPTION_TEXT, e);
                OnSitesLoaded(new EventArgsValue<IEnumerable<IPosterousSite>>(null, e));
            };

            AsyncHelper.RunDelegateAsync((Action) LoadSites, exchandler, null);                        
        }

        public event EventHandler<EventArgsValue<IEnumerable<IPosterousSite>>> SitesLoaded;

        
        #endregion

        
    }
}